/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package de.swta.freezay.database.controller;

import de.swta.freezay.database.controller.exceptions.IllegalOrphanException;
import de.swta.freezay.database.controller.exceptions.NonexistentEntityException;
import de.swta.freezay.database.controller.exceptions.PreexistingEntityException;
import de.swta.freezay.database.dbEntities.Item;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import de.swta.freezay.database.dbEntities.Category;
import de.swta.freezay.database.dbEntities.Unit;
import de.swta.freezay.database.dbEntities.ItemPackage;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Christian
 */
public class ItemJpaController {

    public ItemJpaController() {
        emf = Persistence.createEntityManagerFactory("FreezayPU");
    }
    private EntityManagerFactory emf = null;

    public List<Item> findItemEntities(int maxResults, int firstResult,
            String sortBy, boolean ascending) {

        EntityManager em = getEntityManager();
        try {

            Query q = em.createQuery("select object(o) from Item as o order "
                    + "by o." + sortBy + " " + (ascending ? "ASC" : "DESC"));

            q.setMaxResults(maxResults);
            q.setFirstResult(firstResult);

            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Item item) throws PreexistingEntityException, Exception {
        if (item.getItemPackageCollection() == null) {
            item.setItemPackageCollection(new ArrayList<ItemPackage>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Category category = item.getCategory();
            if (category != null) {
                category = em.getReference(category.getClass(), category.getId());
                item.setCategory(category);
            }
            Unit unit = item.getUnit();
            if (unit != null) {
                unit = em.getReference(unit.getClass(), unit.getId());
                item.setUnit(unit);
            }
            List<ItemPackage> attachedItemPackageCollection = new ArrayList<ItemPackage>();
            for (ItemPackage itemPackageCollectionItemPackageToAttach : item.getItemPackageCollection()) {
                itemPackageCollectionItemPackageToAttach = em.getReference(itemPackageCollectionItemPackageToAttach.getClass(), itemPackageCollectionItemPackageToAttach.getItemPackagePK());
                attachedItemPackageCollection.add(itemPackageCollectionItemPackageToAttach);
            }
            item.setItemPackageCollection(attachedItemPackageCollection);
            em.persist(item);
            if (category != null) {
                category.getItemCollection().add(item);
                category = em.merge(category);
            }
            if (unit != null) {
                unit.getItemCollection().add(item);
                unit = em.merge(unit);
            }
            for (ItemPackage itemPackageCollectionItemPackage : item.getItemPackageCollection()) {
                Item oldItemOfItemPackageCollectionItemPackage = itemPackageCollectionItemPackage.getItem();
                itemPackageCollectionItemPackage.setItem(item);
                itemPackageCollectionItemPackage = em.merge(itemPackageCollectionItemPackage);
                if (oldItemOfItemPackageCollectionItemPackage != null) {
                    oldItemOfItemPackageCollectionItemPackage.getItemPackageCollection().remove(itemPackageCollectionItemPackage);
                    oldItemOfItemPackageCollectionItemPackage = em.merge(oldItemOfItemPackageCollectionItemPackage);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findItem(item.getId()) != null) {
                throw new PreexistingEntityException("Item " + item + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Item item) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Item persistentItem = em.find(Item.class, item.getId());
            Category categoryOld = persistentItem.getCategory();
            Category categoryNew = item.getCategory();
            Unit unitOld = persistentItem.getUnit();
            Unit unitNew = item.getUnit();
            List<ItemPackage> itemPackageCollectionOld = persistentItem.getItemPackageCollection();
            List<ItemPackage> itemPackageCollectionNew = item.getItemPackageCollection();
            List<String> illegalOrphanMessages = null;
            for (ItemPackage itemPackageCollectionOldItemPackage : itemPackageCollectionOld) {
                if (!itemPackageCollectionNew.contains(itemPackageCollectionOldItemPackage)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain ItemPackage " + itemPackageCollectionOldItemPackage + " since its item field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (categoryNew != null) {
                categoryNew = em.getReference(categoryNew.getClass(), categoryNew.getId());
                item.setCategory(categoryNew);
            }
            if (unitNew != null) {
                unitNew = em.getReference(unitNew.getClass(), unitNew.getId());
                item.setUnit(unitNew);
            }
            List<ItemPackage> attachedItemPackageCollectionNew = new ArrayList<ItemPackage>();
            for (ItemPackage itemPackageCollectionNewItemPackageToAttach : itemPackageCollectionNew) {
                itemPackageCollectionNewItemPackageToAttach = em.getReference(itemPackageCollectionNewItemPackageToAttach.getClass(), itemPackageCollectionNewItemPackageToAttach.getItemPackagePK());
                attachedItemPackageCollectionNew.add(itemPackageCollectionNewItemPackageToAttach);
            }
            itemPackageCollectionNew = attachedItemPackageCollectionNew;
            item.setItemPackageCollection(itemPackageCollectionNew);
            item = em.merge(item);
            if (categoryOld != null && !categoryOld.equals(categoryNew)) {
                categoryOld.getItemCollection().remove(item);
                categoryOld = em.merge(categoryOld);
            }
            if (categoryNew != null && !categoryNew.equals(categoryOld)) {
                categoryNew.getItemCollection().add(item);
                categoryNew = em.merge(categoryNew);
            }
            if (unitOld != null && !unitOld.equals(unitNew)) {
                unitOld.getItemCollection().remove(item);
                unitOld = em.merge(unitOld);
            }
            if (unitNew != null && !unitNew.equals(unitOld)) {
                unitNew.getItemCollection().add(item);
                unitNew = em.merge(unitNew);
            }
            for (ItemPackage itemPackageCollectionNewItemPackage : itemPackageCollectionNew) {
                if (!itemPackageCollectionOld.contains(itemPackageCollectionNewItemPackage)) {
                    Item oldItemOfItemPackageCollectionNewItemPackage = itemPackageCollectionNewItemPackage.getItem();
                    itemPackageCollectionNewItemPackage.setItem(item);
                    itemPackageCollectionNewItemPackage = em.merge(itemPackageCollectionNewItemPackage);
                    if (oldItemOfItemPackageCollectionNewItemPackage != null && !oldItemOfItemPackageCollectionNewItemPackage.equals(item)) {
                        oldItemOfItemPackageCollectionNewItemPackage.getItemPackageCollection().remove(itemPackageCollectionNewItemPackage);
                        oldItemOfItemPackageCollectionNewItemPackage = em.merge(oldItemOfItemPackageCollectionNewItemPackage);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = item.getId();
                if (findItem(id) == null) {
                    throw new NonexistentEntityException("The item with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Item item;
            try {
                item = em.getReference(Item.class, id);
                item.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The item with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<ItemPackage> itemPackageCollectionOrphanCheck = item.getItemPackageCollection();
            for (ItemPackage itemPackageCollectionOrphanCheckItemPackage : itemPackageCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Item (" + item + ") cannot be destroyed since the ItemPackage " + itemPackageCollectionOrphanCheckItemPackage + " in its itemPackageCollection field has a non-nullable item field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Category category = item.getCategory();
            if (category != null) {
                category.getItemCollection().remove(item);
                category = em.merge(category);
            }
            Unit unit = item.getUnit();
            if (unit != null) {
                unit.getItemCollection().remove(item);
                unit = em.merge(unit);
            }
            em.remove(item);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public boolean isUsed(Integer id) {
        boolean inUse = false;

        Item itemToTest = this.findItem(id);

        if (itemToTest != null) {
            inUse = itemToTest.getItemPackageCollection().size() != 0;
        }
        return inUse;
    }

    public List<Item> findItemEntities() {
        return findItemEntities(true, -1, -1);
    }

    public List<Item> findItemEntities(int maxResults, int firstResult) {
        return findItemEntities(false, maxResults, firstResult);
    }

    private List<Item> findItemEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Item as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Item findItem(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Item.class, id);
        } finally {
            em.close();
        }
    }

    public int getItemCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Item as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
